<?php
namespace App\Services\Admin;

use App\Models\AdminModel;
use App\Services\BaseService;

/**
 * 后台登录服务
 */
class LoginService extends BaseService
{
    /**
     * 系统登录
     * $param 参数
     * @return array
     */
    public static function login($param = [])
    {
        if(!$param) return AdminModel::result("", 500, "系统繁忙，请重试");
        // 账号
        $account = trim($param['account']);
        // 密码
        $password = trim($param['password']);
        // 用户验证
        $map['account'] = $account;
        $res = AdminModel::where($map)->first(['id','account','status','login_count','password']);
        if (!$res) {
            return AdminModel::result('',500,'账号或密码错误');
        }
        if($res['status'] == 0) return AdminModel::result("", 500, "账号已禁用，请联系管理员启用");
        if(!password_verify($password,$res['password'])){
            return AdminModel::result('',500,'账号或密码不正确');
        }
        try {
            AdminModel::startTrans();
            $unique = md5(uniqid());
            $arr = AdminModel::where("id", $res['id'])->update([
                'last_ip' => request()->ip(),
                'last_time' => time(),
                'unique' => $unique,
                'login_count' => $res['login_count'] + 1
            ]);
            if($arr) {
                AdminModel::commit();
                session(['adminInfo'=>$res,'adminId'=>$unique]);
            }
            return AdminModel::result("", 200, "登录成功");
        } catch (\Exception $e) {
            AdminModel::rollback();
            return AdminModel::result("", 500, $e->getMessage());
        }
    }

    /**
     * 检测登陆状态
     * @return void
     */
    public static function loginCheck()
    {
        try{
            $adminId = session("adminId");
            if(!$adminId) return false;
            $res = AdminModel::where(['unique' => $adminId])->first(['unique','real_name','last_time']);
            if(!$res) return false;
            $end_time = $res['last_time'] + 86400;//过期时间
            if(time() > $end_time) return false;
            return $res;
        }catch (\Exception $e){
            return false;
        }
    }
}
